package ru.btabank.dom.xpath.expression;

import java.util.ArrayList;

import ru.btabank.dom.xpath.XPathException;

public class BooleanFunction extends FunctionCall {
    public BooleanFunction() {
        super();
    }

    public Object evaluate(NodeSet context) throws XPathException {
        ArrayList values = super.evaluateValues(context);
        Object value;

        if (values.size() != 1)
            throw new XPathException("boolean() function requires one argument.");
        else
            value = values.get(0);

        if (value instanceof NodeSet) {
            NodeSet nodeSet = (NodeSet)value;
            return new Boolean(nodeSet.getLength() > 0);
        } else if (value instanceof String) {
            String string = (String)value;
            return new Boolean(string.length() > 0);
        } else if (value instanceof Double) {
            Double number = (Double)value;
            return new Boolean(number.doubleValue() != 0);
        } else if (value instanceof Boolean) {
            return value;
        }
        return new Boolean(value != null);
    }
}
